package com.eqdd.yiqidian.ui.gongneng.renshi.meeting

import android.app.Activity
import android.content.Intent
import android.support.v7.widget.RecyclerView
import android.view.View
import com.bigkoo.pickerview.TimePickerView
import com.eqdd.yiqidian.R
import com.eqdd.yiqidian.adapter.slimadapter.SlimInjector
import com.eqdd.yiqidian.base.Config
import com.eqdd.yiqidian.bean.DepartmentStaffTreeBean
import com.eqdd.yiqidian.bean.rebuild.slimedit.SlimEditCheckButtonBean
import com.eqdd.yiqidian.bean.rebuild.slimedit.SlimEditEnterBean
import com.eqdd.yiqidian.bean.rebuild.slimedit.SlimTimeSelectBean
import com.eqdd.yiqidian.http.DialogCallBack
import com.eqdd.yiqidian.http.HttpConfig
import com.eqdd.yiqidian.http.HttpResult
import com.eqdd.yiqidian.ui.MultiSelectListActivity
import com.eqdd.yiqidian.ui.base.SlimBaseMultiEditActivity
import com.eqdd.yiqidian.ui.tongxunlu.stafftree.StaffTreeMultiActivity
import com.eqdd.yiqidian.ui.tongxunlu.stafftree.StaffTreeSingleActivity
import com.eqdd.yiqidian.utils.ToastUtil
import com.eqdd.yiqidian.widget.ChooseAlertView
import com.jhj.datalibrary.tree.multi.BaseMultiTreeActivity
import com.kyleduo.switchbutton.SwitchButton
import com.lzy.okgo.OkGo
import com.lzy.okgo.model.Response
import kotlinx.android.synthetic.main.activity_recyclerview.*
import org.jetbrains.anko.startActivityForResult
import org.jetbrains.anko.toast
import java.text.SimpleDateFormat
import java.util.*

class MeetingTypeAddActivity : SlimBaseMultiEditActivity() {

    private var upDate: Date? = null
    private var downDate: Date? = null
    private var isUpper: Boolean = false

    private var person: List<DepartmentStaffTreeBean>? = null
    private var month: String? = null
    private var week: String? = null


    override fun initBinding() {
        clearData()
        setContentView(R.layout.activity_recyclerview)
        initTopTitleBar(View.VISIBLE, "会议类型")
        initTopRightText("新增") { v ->
            if (!checkParams()) {
                toast(msg)
                return@initTopRightText
            }
            val bean = slimAdapterEx.data
            OkGo.post<HttpResult<*>>(HttpConfig.BASE_URL + HttpConfig.MEETING_TYPE_ADD)
                    .params("userGuid", user.guid)
                    .params("comid", user.companyId)
                    .params("type", bean[0].content)
                    .params("frequency", (bean[1].tag as? Int)?.toString())
                    .params("timeInterval", bean[2].content)
                    .params("startTime", bean[3].content)
                    .params("endTime", bean[4].content)
                    .params("place", bean[5].content)
                    .params("attendees", bean[6].tag as? String)
                    .params("compere", bean[7].tag as? String)
                    .params("recorder", bean[8].tag as? String)
                    .params("aim", bean[9].content)
                    .params("admin", bean[10].tag as? String)
                    .params("motion", (bean[11] as? SlimEditCheckButtonBean)?.isCheck == true)
                    .execute(object : DialogCallBack<HttpResult<*>>(this) {
                        override fun onSuccess(response: Response<HttpResult<*>>) {
                            val httpResult = response.body()
                            ToastUtil.showShort(httpResult.msg)
                            if (httpResult.status == 200) {
                                clearData()
                                setResult(Activity.RESULT_OK)
                                finish()
                            }
                        }
                    })

        }


    }

    override fun initRecyclerView(): RecyclerView {
        return recyclerView
    }

    private var frequency: String = ""

    override fun itemClick(p: Int) {
        when (slimAdapterEx.data[p].position) {
            1 -> {
                val array = arrayOf("每月", "每周", "每天", "一次")
                ChooseAlertView.getBottomChoose(this, null, array) { o, pos ->
                    if (frequency != array[pos - 1]) {
                        slimAdapterEx.getDataItem(2).content = ""
                        slimAdapterEx.notifyItemChanged(2)
                        month = null
                        week = null
                    }
                    frequency = array[pos - 1]
                    slimAdapterEx.getDataItem(1).content = array[pos - 1]
                    slimAdapterEx.getDataItem(1).tag = pos
                    slimAdapterEx.notifyItemChanged(1)
                    if (pos == 4) {
                        slimAdapterEx.getDataItem(2).content = "一次"
                        slimAdapterEx.notifyItemChanged(2)
                    }
                    slimAdapterEx.getDataItem(1).content
                }.show()

            }
            2 -> {
                val tag = slimAdapterEx.getDataItem(1).tag as? Int
                if (tag == null) {
                    toast("请选择会议频率")
                    return
                }
                when (tag) {
                    1 -> {
                        val array = resources.getStringArray(R.array.month)
                        startActivityForResult<MultiSelectListActivity>(997, "data" to array, "select" to month, Config.TITLE to "会议时段")
                    }
                    2 -> {
                        val array = resources.getStringArray(R.array.week)
                        startActivityForResult<MultiSelectListActivity>(998, "data" to array, "select" to week, Config.TITLE to "会议时段")
                    }
                    3 -> {
                        val array = arrayOf("上午", "下午")
                        ChooseAlertView.getBottomChoose(this, null, array) { o, pos ->
                            slimAdapterEx.getDataItem(2).content = array[pos - 1]
                            slimAdapterEx.notifyItemChanged(2)
                        }.show()
                    }
                }


            }
            3 -> {
                isUpper = true
                openTimePicker()
            }
            4 -> {
                isUpper = false
                openTimePicker()
            }
            6 -> {
                startActivityForResult<StaffTreeMultiActivity>(999, Config.TITLE to "参与人员", Config.ID to 0, Config.TYPE to StaffTreeMultiActivity.TYPE_CANYUREN, BaseMultiTreeActivity.SELECTED_DATA to person)
            }
            7 -> {
                startActivityForResult<StaffTreeSingleActivity>(1000, Config.TITLE to "主持人", Config.ID to 0, Config.TYPE to StaffTreeSingleActivity.TYPE_SINGLE_SELECT)
            }
            8 -> {
                startActivityForResult<StaffTreeSingleActivity>(1001, Config.TITLE to "记录人", Config.ID to 0, Config.TYPE to StaffTreeSingleActivity.TYPE_SINGLE_SELECT)
            }
            10 -> {
                startActivityForResult<StaffTreeSingleActivity>(1002, Config.TITLE to "发布人", Config.ID to 0, Config.TYPE to StaffTreeSingleActivity.TYPE_SINGLE_SELECT)
            }


        }
    }


    override fun setEditBeans() {
        datas.add(SlimEditEnterBean("会议类型", "", 0, "请输入").setNeed(true))
        datas.add(SlimEditEnterBean("会议频率", "", 1, "请选择").setDeal(true).setNeed(true))
        datas.add(SlimEditEnterBean("会议时段", "", 2, "请选择").setDeal(true).setNeed(true))
        datas.add(SlimTimeSelectBean("会议开始时间", "", 3, "请选择").setStartTime(true).setDeal(true).setNeed(true))
        datas.add(SlimTimeSelectBean("会议结束时间", "", 4, "选择择").setStartTime(false).setDeal(true).setNeed(true))
        datas.add(SlimEditEnterBean("会议地点", "", 5, "请输入").setNeed(true))
        datas.add(SlimEditEnterBean("参与人员", "", 6, "请选择").setDeal(true).setNeed(true))
        datas.add(SlimEditEnterBean("主持人", "", 7, "请选择").setDeal(true).setNeed(true))
        datas.add(SlimEditEnterBean("记录人", "", 8, "请选择").setDeal(true).setNeed(true))
        datas.add(SlimEditEnterBean("会议目的", "", 9, "请输入").setNeed(true))
        datas.add(SlimEditEnterBean("会议通知发布人", "", 10, "请选择").setDeal(true).setNeed(true))
        datas.add(SlimEditCheckButtonBean("是否提预案", "", 11, false).setDeal(true))
        slimAdapterEx
                .register(R.layout.list_item_24, SlimInjector<SlimEditCheckButtonBean> { data, injector ->
                    injector?.text(R.id.tv_left_center_content, data?.title)
                            ?.checked(R.id.sb_end, data?.isCheck == true)
                            ?.with<SwitchButton>(R.id.sb_end) {
                                it.setOnCheckedChangeListener { view, isChecked ->
                                    (slimAdapterEx.getDataItem(11) as SlimEditCheckButtonBean).isCheck = isChecked
                                }
                            }

                })

        slimAdapterEx.register(R.layout.list_item_29, SlimInjector<SlimTimeSelectBean> { data, injector ->
            injector?.text(R.id.tv_left_content, data?.title)
                    ?.text(R.id.tv_right_content, data?.content)
                    ?.hint(R.id.tv_right_content, data?.hint)
        })
    }


    private fun openTimePicker() {
        val sf = SimpleDateFormat("HH:mm", Locale.CHINA)
        val now = Calendar.getInstance()
        if (isUpper && upDate != null) {
            now.time = upDate
        } else if (downDate != null) {
            now.time = downDate
        } else {
            now.time = Date()
        }
        TimePickerView.Builder(this, TimePickerView.OnTimeSelectListener { date, v ->
            if (isUpper) {
                upDate = date
                if (downDate != null && upDate?.after(downDate) == true) {
                    toast("开始时间小于结束事件，请重新选择")
                    return@OnTimeSelectListener
                }
                slimAdapterEx.getDataItem(3).content = sf.format(date)
                slimAdapterEx.notifyItemChanged(3)
            } else {
                downDate = date
                if (upDate != null && upDate?.after(downDate) == true) {
                    ToastUtil.showShort("开始时间小于结束事件，请重新选择")
                    return@OnTimeSelectListener
                }
                slimAdapterEx.getDataItem(4).content = sf.format(date)
                slimAdapterEx.notifyItemChanged(4)
            }

        })
                .setOutSideCancelable(true)
                .setType(booleanArrayOf(false, false, false, true, true, false))
                .setDate(now)
                .build()
                .show()
    }


    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (data == null)
            return
        if (resultCode == RESULT_OK) {
            when (requestCode) {
                997 -> {
                    month = data.getStringExtra("data")
                    datas[2].content = month
                    slimAdapterEx.notifyItemChanged(2)
                }
                998 -> {
                    week = data.getStringExtra("data")
                    datas[2].content = week
                    slimAdapterEx.notifyItemChanged(2)
                }
                999 -> {//参与人员
                    person = data.getSerializableExtra(BaseMultiTreeActivity.SELECTED_DATA) as? List<DepartmentStaffTreeBean>
                    val id = StringBuilder()
                    val name = StringBuilder()
                    person?.forEach {
                        id.append(it.id).append(",")
                        name.append(it.name).append(",")
                    }
                    datas[6].content = name.substring(0, name.length - 1)
                    datas[6].tag = id.substring(0, id.length - 1)
                    slimAdapterEx.notifyItemChanged(6)
                }
                1000 -> {//主持人
                    val hostMan = data.getSerializableExtra("data") as DepartmentStaffTreeBean?
                    datas[7].content = hostMan?.name
                    datas[7].tag = hostMan?.id
                    slimAdapterEx.notifyItemChanged(7)

                }
                1001 -> {//记录人
                    val recordMan = data.getSerializableExtra("data") as DepartmentStaffTreeBean?
                    datas[8].content = recordMan?.name
                    datas[8].tag = recordMan?.id
                    slimAdapterEx.notifyItemChanged(8)
                }
                1002 -> {//发布人
                    val publishMan = data.getSerializableExtra("data") as DepartmentStaffTreeBean?
                    datas[10].content = publishMan?.name
                    datas[10].tag = publishMan?.id
                    slimAdapterEx.notifyItemChanged(10)
                }
            }
        }
    }

}
